package com.suray.rgv.son.mother.manual;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.basic.wcs.utils.thread.BaseThread;
import com.suray.rgv.son.mother.core.RgvSonControl;
import com.suray.rgv.son.mother.util.RgvSMLogger;
import com.suray.rgv.son.mother.util.RgvSonMoveBySpeedStatus;
import com.suray.rgv.son.util.RgvSonLogger;

/**
 * 子车手动行驶线程
 */
public class RgvSonMoveBySpeedThread extends BaseThread {
    //子车按速度行驶
    private RgvSonMoveBySpeedStatus sonRgvSpeedMove;

    //按速度行驶方向
    private int direction;

    private RgvSonControl rgvSonControl;

    public RgvSonMoveBySpeedThread(RgvSonControl rgvSonControl) {
        super("子车按速度行驶", 1000, RgvSonMoveBySpeedThread.class);

        this.rgvSonControl = rgvSonControl;
        sonRgvSpeedMove = RgvSonMoveBySpeedStatus.STANDY;
    }

    @Override
    protected void process() {
        try {
            while (sonRgvSpeedMove == RgvSonMoveBySpeedStatus.MOVE_BY_SPEED) {
                RgvSMLogger.info(LoggerType.MOVE_BY_SPEED, rgvSonControl.getSeries(), sonRgvSpeedMove,
                        "开始按速度行驶", this.getClass());
                rgvSonControl.sonRgvMoveBySpeed(direction);
                WcsFuncUtil.delay(100);
            }
            if (sonRgvSpeedMove == RgvSonMoveBySpeedStatus.STOP_MOVE_BY_SPEED) {
                rgvSonControl.stopSonRgvMoveBySpeed();
                sonRgvSpeedMove = RgvSonMoveBySpeedStatus.STANDY;
                RgvSMLogger.info(LoggerType.MOVE_BY_SPEED, rgvSonControl.getSeries(), sonRgvSpeedMove,
                        "按速度停止成功", this.getClass());
            }
        } catch (RuntimeException e) {
            RgvSMLogger.info(LoggerType.ERROR, rgvSonControl.getSeries(), sonRgvSpeedMove, e.getMessage(),
                    this.getClass());
            sonRgvSpeedMove = RgvSonMoveBySpeedStatus.STANDY;
        }
    }

    /**
     * 按速度停止
     */
    public void stopSpeedMove() {
        synchronized (sonRgvSpeedMove) {
            if (sonRgvSpeedMove == RgvSonMoveBySpeedStatus.MOVE_BY_SPEED) {
                sonRgvSpeedMove = RgvSonMoveBySpeedStatus.STOP_MOVE_BY_SPEED;
            }
        }
        RgvSonLogger.info(LoggerType.MOVE_BY_SPEED, rgvSonControl.getSeries(), sonRgvSpeedMove, "按速度停止",
                this.getClass());
    }

    /**
     * 按速度行驶
     */
    public void startSpeedMove(int direction) {
        synchronized (sonRgvSpeedMove) {
            this.direction = direction;
            sonRgvSpeedMove = RgvSonMoveBySpeedStatus.MOVE_BY_SPEED;
        }
        RgvSonLogger.info(LoggerType.MOVE_BY_SPEED, rgvSonControl.getSeries(), sonRgvSpeedMove, "按速度行驶",
                this.getClass());
    }

    /**
     * 初始化按速度行驶
     */
    private synchronized void initSpeedMove() {
        if (sonRgvSpeedMove == RgvSonMoveBySpeedStatus.STOP_MOVE_BY_SPEED) {
            sonRgvSpeedMove = RgvSonMoveBySpeedStatus.STANDY;
        }
    }
}
